import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/mine/view_mycomment.dart';
import 'package:flutter_chip/view/mine/view_mygoods.dart';
import 'package:flutter_chip/view/mine/view_mytopic.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/view_image.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_chip/widget/widget_sliver_delegate.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';

class UserInfoPage extends StatefulWidget {
  final String userId;
  final bool isSelf;

  UserInfoPage(this.userId, this.isSelf);

  @override
  _UserInfoPageState createState() => _UserInfoPageState();
}

class _UserInfoPageState extends StateWithLifecycle<UserInfoPage>
    with TickerProviderStateMixin {
  User user;
  User myUser;

  PageController pageController;
  TabController tabController;
  int page = 0;
  var isPageCanChanged = true;
  bool _loading = false;
  String _msg = "加载中...";
  bool isFollow = false;
  int fansNum = 0;
  int followNum = 0;
  int sellerNum = 0;

  List tabs = [
    {"title": "商品", "num": 0},
    {"title": "帖子", "num": 0},
    {"title": "评价", "num": 0}
  ];
  List<Widget> _tabPages = [];

  @override
  void initState() {
    super.initState();
    _tabPages.add(MyGoodsPage(userId: widget.userId, isSelf: widget.isSelf));
    _tabPages.add(MyTopicPage(userId: widget.userId, isSelf: widget.isSelf));
    _tabPages.add(CommentPage(userId: widget.userId));
    pageController = PageController(initialPage: this.page);
    tabController = TabController(length: tabs.length, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        onPageChange(tabController.index, p: pageController);
      }
    });
  }

  @override
  void onResume() {
    super.onResume();
    _initDatas();
    _isFollow();
    _queryUserNum();
  }

  ///获取用户信息
  void _initDatas() async {
    String url = '${Api.URL_INFO}?userId=${widget.userId}';
    Http.get(url, successCallBack: (data) {
      setState(() {
        user = User.fromJson(json.decode(data));
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ProgressDialog(
        msg: _msg,
        loading: _loading,
        child: NestedScrollView(
          headerSliverBuilder: _headerSliver,
          body: PageView(
            onPageChanged: (index) {
              if (isPageCanChanged) {
                onPageChange(index);
              }
            },
            controller: pageController,
            children: tabs.asMap().keys.map((index) {
              return _tabPages[index];
            }).toList(),
          ),
        ),
      ),
    );
  }

  List<Widget> _headerSliver(BuildContext context, bool innerBoxIsScrolled) {
    Widget child;
    if (null == user || null == user.headBg) {
      child = Image.asset(
        Comm.IMG_USER_BG,
        fit: BoxFit.cover,
        height: 286,
        width: MediaQuery.of(context).size.width,
      );
    } else {
      child = CachedNetworkImage(
        imageUrl: Api.getUrl(user.headBg),
        fit: BoxFit.cover,
        height: 286,
        width: MediaQuery.of(context).size.width,
      );
    }
    return <Widget>[
      SliverAppBar(
        pinned: true,
        primary: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: true,
        title: Text(
          widget.isSelf ? '我的主页' : 'TA的主页',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        expandedHeight: 250,
        flexibleSpace: FlexibleSpaceBar(
          collapseMode: CollapseMode.pin,
          background: Stack(fit: StackFit.loose, children: <Widget>[
            child,
            Container(
              margin: EdgeInsets.only(top: 90, left: 10, right: 10, bottom: 10),
              decoration: BoxDecoration(
                  color: Color(0xCFFFFFFF), borderRadius: BorderRadius.circular(10)),
              padding: EdgeInsets.only(top: 10, bottom: 10),
              height: double.maxFinite,
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    _widgetBtn(),
                    _topWidget(),
                    SizedBox(height: 2),
                    _centerWidget(),
                    SizedBox(height: 2),
                    _bottomWidget()
                  ]),
            ),
            _getHeadWidget(),
          ]),
        ),
      ),
      SliverPersistentHeader(
          pinned: true,
          delegate: SliverAppBarDelegate(
              maxHeight: 40,
              minHeight: 40,
              child: Container(
                color: Colors.white,
                child: TabBar(
                  labelColor: Theme.of(context).accentColor,
                  unselectedLabelColor: Colors.grey,
                  indicatorSize: TabBarIndicatorSize.label,
                  tabs: tabs.map((item) {
                    return _tabWidget(item);
                  }).toList(),
                  controller: tabController,
                ),
              )))
    ];
  }

  Widget _tabWidget(var item) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        Text(item["title"]),
        Text(
          '(${item["num"]})',
          style: TextStyle(fontSize: 12),
        )
      ],
    );
  }

  ///用户头像获取
  Widget _getHeadWidget() {
    return GestureDetector(
      child: Container(
        width: 64,
        height: 64,
        margin: EdgeInsets.only(top: 56, left: 40),
        child: ClipOval(
            child: CachedNetworkImage(
          imageUrl: Api.getUrl(null != user ? user.imgUrl : ""),
          fit: BoxFit.cover,
          errorWidget: (context, url, error) =>
              Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
        )),
        decoration: BoxDecoration(
            color: Theme.of(context).accentColor,
            border: Border.all(color: Colors.white, width: 2),
            borderRadius: BorderRadius.circular(32)),
      ),
      onTap: () {
        if (null != user && null != user.imgUrl) {
          List<String> images = [user.imgUrl];
          Navigator.of(context).push(RouteSlide(ImagePage(images)));
        }
      },
    );
  }

  ///卡片关注编辑按钮
  Widget _widgetBtn() {
    //私信按钮
    Widget _sxWidget = GestureDetector(
      child: Container(
        height: 24,
        alignment: Alignment.center,
        margin: EdgeInsets.only(right: 10),
        padding: EdgeInsets.only(left: 6, right: 6),
        decoration: BoxDecoration(
            color: Colors.lightBlue, borderRadius: BorderRadius.circular(6)),
        child: Text(
          '私信',
          style: TextStyle(color: Colors.white, fontSize: 14),
        ),
      ),
      onTap: () {
        var jsons = jsonEncode(Utf8Encoder().convert(json.encode(user)));
        String url = '${Routers.PAGE_CHAT}?user=$jsons';
        Routers.router
            .navigateTo(context, url, transition: TransitionType.inFromRight);
      },
    );

    //用戶二维码
    Widget _qrCodeWidget = GestureDetector(
      onTap: () {
        Routers.router.navigateTo(
            context, "${Routers.PAGE_QRCODE}?sellerNum=$sellerNum",
            transition: TransitionType.inFromRight);
      },
      child: Container(
        width: 30,
        height: 30,
        margin: EdgeInsets.only(right: 10, left: 10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18),
          border: Border.all(width: 1.5, color: Theme.of(context).accentColor),
        ),
        child: Image.asset(
          Comm.IMG_QR_CODE,
          width: 18,
          height: 18,
          color: Theme.of(context).accentColor,
        ),
      ),
    );

    //关注按钮
    Widget _followWidget = GestureDetector(
      child: Container(
        height: 24,
        alignment: Alignment.center,
        margin: EdgeInsets.only(right: 10),
        padding: EdgeInsets.only(left: 6, right: 6),
        decoration: BoxDecoration(
            color: Colors.lightBlue, borderRadius: BorderRadius.circular(6)),
        child: Text(
          isFollow ? "√已关注" : '+关注',
          style: TextStyle(color: Colors.white, fontSize: 14),
        ),
      ),
      onTap: () {
        _followUser();
      },
    );

    //编辑资料
    Widget _editWidget = GestureDetector(
        child: Container(
          height: 28,
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 10, right: 10),
          decoration: BoxDecoration(
              border: Border.all(color: Theme.of(context).accentColor),
              borderRadius: BorderRadius.circular(16)),
          child: Text(
            '编辑资料',
            style:
                TextStyle(color: Theme.of(context).accentColor, fontSize: 14),
          ),
        ),
        onTap: () {
          Routers.router.navigateTo(context, Routers.PAGE_MINE_EDIT,
              transition: TransitionType.inFromRight);
        });
    return Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
      Offstage(offstage: widget.isSelf, child: _followWidget),
      Offstage(offstage: widget.isSelf || !isFollow, child: _sxWidget),
      Offstage(offstage: !widget.isSelf, child: _editWidget),
      Offstage(offstage: !widget.isSelf, child: _qrCodeWidget),
    ]);
  }

  ///卡片顶部组件 用户名称、编辑资料、是否认证
  Widget _topWidget() {
    bool isNull =
        null == user || null == user.userName || user.userName.isEmpty;
    Color vipColor =
        null != user && user.vip == 1 ? Color(0xffFFCE40) : Colors.grey;
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(width: 20),
          Container(
            alignment: Alignment.bottomLeft,
            child: Text(isNull ? " " : '${user.userName}',
                style: TextStyle(fontSize: 20)),
          ),
          Image.asset(
            Comm.IMG_IC_VIP,
            width: 18,
            height: 18,
            color: vipColor,
          ),
          SizedBox(width: 10),
          Offstage(
            offstage: true,
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10, bottom: 4),
              child: Container(
                padding: EdgeInsets.only(left: 2, right: 2),
                decoration: BoxDecoration(
                    color: Colors.redAccent,
                    borderRadius: BorderRadius.circular(4)),
                child: Text(
                  '已认证',
                  style: TextStyle(color: Colors.white, fontSize: 8),
                ),
              ),
            ),
          )
        ]);
  }

  ///获取个人简介
  Widget _centerWidget() {
    bool isNull =
        null == user || null == user.introduce || user.introduce.isEmpty;
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
      SizedBox(width: 20),
      Expanded(
          child: Text(isNull ? "这个人很懒，什么也没留下！" : '${user.introduce}',
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 14, color: Color(0xff999999))))
    ]);
  }

  ///收藏关注粉丝
  Widget _bottomWidget() {
    return Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: <
        Widget>[
      Expanded(
          child: GestureDetector(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '$followNum',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              Text('关注', style: TextStyle(color: Color(0xff777777)))
            ]),
        onTap: () {
          String url = "${Routers.PAGE_USER_LIST}?type=1&userId=" + user.userId;
          Routers.router
              .navigateTo(context, url, transition: TransitionType.inFromRight);
        },
      )),
      Expanded(
          child: GestureDetector(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('$fansNum', style: TextStyle(fontWeight: FontWeight.bold)),
              Text('粉丝', style: TextStyle(color: Color(0xff777777)))
            ]),
        onTap: () {
          String url = "${Routers.PAGE_USER_LIST}?type=2&userId=" + user.userId;
          Routers.router
              .navigateTo(context, url, transition: TransitionType.inFromRight);
        },
      )),
      Expanded(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
            Text('0', style: TextStyle(fontWeight: FontWeight.bold)),
            Text('收藏', style: TextStyle(color: Color(0xff777777)))
          ])),
    ]);
  }

  ///页面滑动监听
  onPageChange(int index, {PageController p, TabController t}) async {
    if (p != null) {
      //判断是哪一个切换
      isPageCanChanged = false;
      await pageController.animateToPage(index,
          duration: Duration(milliseconds: 500),
          curve: Curves.ease); //等待pageview切换完毕,再释放pageivew监听
      isPageCanChanged = true;
    } else {
      tabController.animateTo(index); //切换Tabbar
    }
  }

  ///关注用户
  void _followUser() async {
    setState(() {
      _msg = "操作中...";
      _loading = true;
    });
    String url = "${Api.URL_FOLLOW_ADD}?userId=${user.userId}";
    Http.post(url, successCallBack: (data) {
      Toast.show("操作成功");
      setState(() {
        _loading = false;
        isFollow = !isFollow;
      });
    }, errorCallBack: (error) {
      Toast.show(error);
      setState(() {
        _loading = false;
      });
    });
  }

  ///是否已关注
  void _isFollow() async {
    String url = "${Api.URL_FOLLOW_FOLLOWED}?userId=${widget.userId}";
    Http.get(url, successCallBack: (data) {
      if (json.decode(data)["isFollow"] == "Y") {
        setState(() {
          isFollow = true;
        });
      }
    }, errorCallBack: (error) {
      setState(() {
        _loading = false;
      });
    });
  }

  ///查询已关注和粉丝数量
  void _queryUserNum() async {
    String url = "${Api.URL_USER_NUM}?userId=${widget.userId}";
    Http.get(url, successCallBack: (data) {
      setState(() {
        fansNum = json.decode(data)["fansNum"];
        followNum = json.decode(data)["followNum"];
        int goodsNum = json.decode(data)["goodsNum"];
        int topicNum = json.decode(data)["topicNum"];
        int commentNum = json.decode(data)["commentNum"];
        tabs[0]["num"] = goodsNum;
        tabs[1]["num"] = topicNum;
        tabs[2]["num"] = commentNum;
        sellerNum = json.decode(data)["sellerNum"];
      });
    });
  }
}
